<template>
  <div class="payment-container">
    <div class="breadcrumb-container flex-row">
      <breadcrumb />
    </div>
    <el-divider />
    <div class="payment-content">
      <div class="filter-container flex-row">
        <el-input
          v-model="tableListQuery.keyword"
          placeholder="请输入搜索内容"
          prefix-icon="el-icon-search"
          style="width:200px;"
          class="filter-item"
        />
        <el-button class="filter-item" type="primary" @click="getPaymentList">搜索</el-button>
        <el-select
          v-model="tableListQuery.itemId"
          placeholder="请选择费用项目"
          clearable
          class="filter-item"
          style="width:150px;margin-left:15px;"
          @change="getPaymentList"
        >
          <el-option
            v-for="option in paymentItemList"
            :key="option.id"
            :label="option.name"
            :value="option.id"
          />
        </el-select>
        <el-select
          v-model="tableListQuery.status"
          placeholder="请选择状态"
          clearable
          class="filter-item"
          style="width:150px;margin-left:15px;"
          @change="getPaymentList"
        >
          <el-option label="待支付" :value="0" />
          <el-option label="已支付" :value="1" />
          <el-option label="待莱福管家确认是否支付" :value="2" />
          <el-option label="已终止" :value="3" />
        </el-select>
        <el-select
          v-model="tableListQuery.overdueFlag"
          placeholder="请选择是否逾期"
          clearable
          class="filter-item"
          style="width:150px;margin-left:15px;"
          @change="getPaymentList"
        >
          <el-option label="否" :value="0" />
          <el-option label="是" :value="1" />
        </el-select>
        <el-button
          class="filter-item"
          type="primary"
          style="margin-left:auto;"
          @click="addPaymentClick"
        >新增</el-button>
      </div>
      <payment-table :payment-list="paymentList" @handleDetail="paymentDetail" /><br>
      <el-pagination
        :v-show="total > 0"
        background
        :current-page="tableListQuery.page"
        :page-sizes="[10, 20, 50,100]"
        :page-size="tableListQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      title=""
      width="1073px"
      custom-class="myDigo inputTop"
      :show-close="false"
      :visible.sync="showAdd"
      destroy-on-close
      @closed="addDialogClosed"
    >
      <h2>新增缴费<i class="el-icon-close" @click="close" /></h2>
      <div class="digoDiv">
        <el-form
          v-if="showAdd"
          ref="paymentForm"
          :model="paymentForm"
          :label-position="'left'"
          :rules="rules"
          label-width="64px"
          class="formDiv"
        >
          <el-form-item label="房产">
            <el-select v-model="paymentForm.houseId" filterable placeholder="请输入关键字：房产（地址/ID）" style="width:100%;" @change="selectHouse">
              <el-option
                v-for="item in houseList"
                :key="item.id"
                :label="item.address"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <div class="flex-row borbtoonline">
            <el-form-item label="费用项目" style="margin-right:20px">
              <el-select v-model="paymentForm.itemId" filterable placeholder="请输入费用项目" style="width:150px">
                <el-option
                  v-for="option in paymentItemList"
                  :key="option.id"
                  :label="option.name"
                  :value="option.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="费用日期" style="margin-right:20px">
              <el-date-picker
                v-model="daterange"
                type="daterange"
                range-separator="-"
                start-placeholder="请选择起始日"
                end-placeholder="请选择截止日"
                style="width:260px"
                @change="selectDaterange"
              />
            </el-form-item>
          </div>

          <el-form-item label="费用说明">
            <el-input v-model="paymentForm.remark" :rows="4" type="textarea" placeholder="请输入..." />
          </el-form-item>

          <el-form-item label="上传凭证">
            <bill-file-upload
              v-model="paymentForm.filePath"
              dir="payment"
              name="上传凭证"
              :maxcount="10"
              format="png,pdf,jpg,jpeg"
              :urls="paymentForm.filePath"
              @getFile="getFile"
            />
          </el-form-item>

          <div class="flex-row">
            <el-form-item label="支付费用：" label-width="80px" prop="feeDollar">
              <span style="color:black;font-weight:bold;">$ </span>
              <el-input v-model="paymentForm.feeDollar" placeholder="请输入费用" style="width:120px;margin-right:20px" @change="getCNY" />
            </el-form-item>
            <el-form-item label-width="0px" prop="feeCny">
              <span style="color:black;font-weight:bold;">¥ </span>
              <el-input v-model="paymentForm.feeCny" placeholder="请输入费用" style="width:120px;margin-right:20px" />
            </el-form-item>
            <el-form-item label="支付方式">
              <el-checkbox-group v-model="paymentForm.deductFlag">
                <el-checkbox label="可用租金抵扣" true-label="1" false-label="0" name="type" />
              </el-checkbox-group>
            </el-form-item>
          </div>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" class="dialog-footer-btn" @click="sendPayment">确认发出</el-button>
        <el-button type="info" class="dialog-footer-btn" @click="close">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title=""
      width="1073px"
      custom-class="myDigo inputTop"
      :show-close="false"
      :visible.sync="showView"
    >
      <h2>查看缴费<i class="el-icon-close" @click="showView=false" /></h2>
      <div class="digoDiv">
        <el-form
          ref="paymentForm"
          :model="paymentForm"
          :label-position="'left'"
          label-width="72px"
          class="formDiv"
        >
          <el-form-item label="房产：">
            <div class="dialog-view-text" style="width:100%;">{{ paymentInfo.address }}</div>
          </el-form-item>

          <div class="flex-row borbtoonline">
            <el-form-item label="费用项目：" style="margin-right:20px">
              <div class="dialog-view-text" style="width:150px;">{{ paymentInfo.itemName }}</div>
            </el-form-item>
            <el-form-item label="费用日期：" style="margin-right:20px">
              <div v-if="!paymentInfo.beginDate || !paymentInfo.endDate" class="dialog-view-text">--</div>
              <div v-else class="dialog-view-text" style="width:150px;">{{ dateFormat(paymentInfo.beginDate) }} - {{ dateFormat(paymentInfo.endDate) }}</div>
            </el-form-item>
          </div>

          <el-form-item label="费用说明：">
            <div class="dialog-view-text" style="min-height:4em;line-height:20px;margin-top:8px;">{{ paymentInfo.remark }}</div>
          </el-form-item>

          <el-form-item label="上传凭证：">
            <div v-for="(item, index) in splitFileName(paymentInfo.filePath)" :key="index" class="dialog-view-text file-name" @click="fileClick(item.url)">{{ item.name }}</div>
          </el-form-item>

          <div class="flex-row borbtoonline">
            <el-form-item label="支付费用：" style="margin-right:20px">
              <div class="dialog-view-text" style="width:120px"><span style="font-weight:bold;">$</span>{{ paymentInfo.feeDollar }}（¥ {{ paymentInfo.feeCny }}）</div>
            </el-form-item>
            <el-form-item label="支付方式：">
              <el-checkbox-group v-model="paymentInfo.deductFlag">
                <el-checkbox label="可用租金抵扣" :true-label="1" :false-label="0" name="type" disabled />
              </el-checkbox-group>
            </el-form-item>
          </div>

          <el-form-item label="支付状态：">
            <el-button v-if="paymentInfo.status !== 1" plain type="primary" :disabled="paymentInfo.status === 3" class="form-btn nonbg-btn" @click="confirmPay(paymentInfo.id)">确认已线下支付</el-button>
            <div v-else class="dialog-view-text">
              <span v-if="paymentInfo.type===1">已支付（自行支付）</span>
              <span v-else>
                <span v-if="+paymentInfo.payType===0">已支付（微信支付）</span>
                <span v-else-if="+paymentInfo.payType===1">已支付（租金抵扣）</span>
                <span v-else>已支付（线下支付）</span>
              </span>
            </div>
          </el-form-item>

          <div class="payment-status">
            <span v-if="paymentInfo.status === 0">未支付</span>
            <span v-if="paymentInfo.status === 1">已支付</span>
            <span v-if="paymentInfo.status === 2">待莱福管家确认是否支付</span>
            <span v-if="paymentInfo.status === 3">已终止</span>
          </div>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="info" class="dialog-footer-btn" @click="showView=false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import Breadcrumb from '@/components/Breadcrumb'
import { pageByOperation } from '@/api/house'
import { getFinanceCatalogList, getAustraliaRate } from '@/api/dataConfig'
import { getPaymentList, getPayment, addPayment, confirmPay } from '@/api/payment'
import { dateFormat } from '@/utils/common'
import PaymentTable from './components/PaymentTable.vue'
import BillFileUpload from '@/components/Upload/BillFileUpload.vue'
export default {
  components: {
    Breadcrumb,
    PaymentTable,
    BillFileUpload
  },
  data() {
    const checkFee = (rule, value, callback) => {
      if (!value || +value === 0) {
        callback()
      }
      if (!Number(value * 1)) {
        callback(new Error('请输入数字值'))
      } else {
        if (value * 1 > 999999) {
          callback(new Error('金额不大于999999'))
        } else {
          callback()
        }
      }
    }
    return {
      dateFormat,
      daterange: [],
      value: '',
      houseList: [],
      paymentItemList: [],
      houseListQuery: {
        page: 1,
        limit: 100
      },
      listQuery: {
        keyword: undefined,
        month: undefined,
        property: undefined,
        status: undefined
      },
      paymentList: [],
      tableListQuery: {
        page: 1,
        limit: 10,
        keyword: undefined,
        itemId: undefined,
        status: undefined
      },
      loading: false,
      total: 0,
      showAdd: false,
      showView: false,
      paymentInfo: {},
      defaultForm: {
        houseId: '',
        beginDate: '',
        endDate: '',
        itemId: '',
        remark: '',
        filePath: '',
        deductFlag: '',
        feeDollar: undefined,
        feeCny: undefined
      },
      paymentForm: {
        houseId: '',
        beginDate: '',
        endDate: '',
        itemId: '',
        remark: '',
        filePath: '',
        deductFlag: '',
        feeDollar: undefined,
        feeCny: undefined
      },
      rules: {
        feeDollar: [{ validator: checkFee, trigger: 'blur' }],
        feeCny: [{ validator: checkFee, trigger: 'blur' }]
      },
      australiaRate: 0,
      isConfirmPay: false
    }
  },
  watch: {
    paymentForm: {
      handler(newVal, oldVal) {
        if (newVal.feeDollar === '' || newVal.feeDollar === null) {
          this.paymentForm.feeCny = ''
        }
        if (newVal.feeDollar) {
          this.getCNY(newVal.feeDollar)
        }
      },
      deep: true
    }
  },
  created() {
    this.getPaymentList()
    this.getPaymentItemList()
    this.getAustraliaRate()
    if (this.$route.query.id) {
      this.paymentDetail(this.$route.query.id)
    }
  },
  methods: {
    async addPaymentClick() {
      await this.getHouseList()
      await this.getPaymentItemList()
      this.showAdd = true
    },
    close() {
      this.showAdd = false
    },
    addDialogClosed() {
      this.paymentForm = { ...this.defaultForm }
      this.daterange = []
    },
    selectHouse(val) {
      console.log(val)
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.tableListQuery.page = 1
      this.tableListQuery.limit = val
      this.getPaymentList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.tableListQuery.page = val
      this.getPaymentList()
    },
    selectDaterange(list) {
      this.paymentForm.beginDate = list[0]
      this.paymentForm.endDate = list[1]
    },
    async getHouseList() {
      const res = await pageByOperation(this.houseListQuery)
      if (res.code === 200) {
        this.houseList = res.data.records
      }
    },
    getPaymentList() {
      this.loading = true
      getPaymentList(this.tableListQuery).then(response => {
        this.paymentList = response.data.records
        this.total = response.data.total
        this.loading = false
      })
    },
    async getPaymentItemList() {
      const params = {
        type: 2
      }
      const res = await getFinanceCatalogList(params)
      if (res.code === 200) {
        this.paymentItemList = res.data
        console.log(this.paymentItemList)
      }
    },
    paymentDetail(id) {
      getPayment(id).then(response => {
        this.paymentInfo = response.data
        this.showView = true
      })
    },
    sendPayment() {
      addPayment(this.paymentForm).then(response => {
        this.showAdd = false
        this.paymentForm = { ...this.defaultForm }
        this.daterange = []
        this.getPaymentList()
        this.$notify({
          title: '成功',
          message: '添加成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    confirmPay(id) {
      confirmPay(id).then(response => {
        console.log(response)
        this.isConfirmPay = true
        this.paymentDetail(id)
        this.getPaymentList()
        this.$notify({
          title: '成功',
          message: '确认支付成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    getFile(val) {
      console.log('val.toString():', val.toString())
      this.paymentForm.filePath = val.toString()
    },
    splitFileName(filePath) {
      const fileNameList = []
      if (filePath !== undefined && filePath !== '') {
        const urlList = filePath.split(',')
        urlList.forEach(item => {
          const name = item.split('upload/')[1]
          const url = item
          fileNameList.push({ url, name })
        })
      }
      return fileNameList
    },
    fileClick(url) {
      window.open(url, '_blank')
    },
    async getAustraliaRate() {
      const res = await getAustraliaRate()
      if (res.code === 200) {
        this.australiaRate = res.data.rate || 0
      }
    },
    getCNY(value) {
      if (!this.australiaRate || !Number(value)) {
        return
      }
      this.paymentForm.feeCny = this.ceil(value * this.australiaRate, 2).toString()
    },
    ceil(num, byte) {
      const n = Math.pow(10, byte)
      return Math.ceil(num * n) / n
    }

  }
}
</script>

<style lang="scss">
.payment-container {
  .no-number::-webkit-outer-spin-button,
  .no-number::-webkit-inner-spin-button {
    margin: 0;
    -webkit-appearance: none !important;
  }

  .no-number input[type="number"]::-webkit-outer-spin-button,
  .no-number input[type="number"]::-webkit-inner-spin-button {
    margin: 0;
    -webkit-appearance: none !important;
  }

  /*在firefox下移除input[number]的上下箭头*/
  .no-number {
    -moz-appearance: textfield;
  }

  .no-number input[type="number"] {
    -moz-appearance: textfield;
  }
}

</style>

<style lang="scss" scoped>
.breadcrumb-container {
  position: relative;
  width: 100%;
  height: 60px;
  padding: 0 14px;

  &::after {
    content: '';
    position: absolute;
    left: 0px;
    top: 50%;
    width: 2px;
    height: 37px;
    background-color: #5AC6B7;
    transform: translateY(-50%);
  }
}

.payment-content {
  padding: 10px;
}

.myDigo h2 {
  height: 32px;
  background: #343436;
}

.form-btn {
  height: 32px;
  padding: 0 12px;
  font-size: 12px;
}

::v-deep .myDigo .el-dialog__footer {
  background: #e5e9ed;
  padding-top: 20px;
}

::v-deep .el-dialog.myDigo .el-dialog__body {
  padding: 0;
}

::v-deep .el-dialog.myDigo .el-dialog__header {
  display: none;
}

.el-dialog.myDigo h2 {
  height: 58px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 39px;
  padding-right: 39px;
  color: #fff;
  font-size: 18px;
  padding-top: 0;
  margin-top: 0;
  overflow: hidden;
  font-weight: normal;
  font-family: "SourceHanSansSC-regular";
}

.el-dialog.myDigo h2 i {
  font-size: 26px;
  cursor: pointer;
}

::v-deep .el-dialog.myDigo .el-dialog__body {
  text-align: left;
}

.digoDiv ::v-deep .el-input--medium .el-input__inner {
    height: 32px;
    line-height: 32px;
    text-indent: 5px;
}

::v-deep .inputTop input::-webkit-input-placeholder,
textarea::-webkit-input-placeholder,
select::-webkit-input-placeholder {
  font-size: 12px;
}

::v-deep .inputTop input:-moz-placeholder,
textarea:-moz-placeholder,
select::-webkit-input-placeholder {
  font-size: 12px;
}

::v-deep .inputTop input::-moz-placeholder,
textarea::-moz-placeholder,
select::-webkit-input-placeholder {
  font-size: 12px;
}

::v-deep .inputTop input:-ms-input-placeholder,
textarea:-ms-input-placeholder,
select::-webkit-input-placeholder {
  font-size: 12px;
}

::v-deep .el-form-item {
  margin-bottom: 16px;
}

::v-deep .el-form-item--medium .el-form-item__label {
  color: #101010;
  font-size: 12px;
  font-weight: bold;
}

::v-deep .el-checkbox-group {
  height: 36px;

  .el-checkbox__label {
    font-size: 12px;
    color: #353535;
    font-weight: normal;
  }
}

::v-deep .el-checkbox__input.is-disabled + span.el-checkbox__label {
  font-size: 12px;
  color: #353535;
  font-weight: normal;
}

.nonbg-btn {
  background: none;
}

.mtright {
  margin-right: 11px;
}

.formDiv {
  position: relative;
  padding-left: 39px;
  padding-right: 39px;
  overflow: hidden;
}

.borbtoonline {
  padding-bottom: 20px;
  margin-bottom: 20px;
  position: relative;
}

.borbtoonline::after {
  content: "";
  position: absolute;
  left: -51px;
  bottom: 0;
  width: 111%;
  height: 1px;
  background: #f0f0f0;
}

.borbtoonline .el-form-item {
  margin-bottom: 0;
}

.el-icon-remove-outline {
  margin-left: 20px;
  display: inline-block;
  color: #5AC6B7;
  font-weight: bold;
  transform: scale(1.5);
}

.white-bg-btn {
  background: #fff;
}

.dialog-footer-btn {
  width: 100px;
}

.form-note-text {
  font-size: 12px;
  font-weight: bold;
  color: #101010;
}

.dialog-content {
  height: 150px;
  padding: 0 60px;
  align-items: center;
}

.warning-icon {
  margin-right: 20px;
  height: 24px;
  width: 24px;
  fill: #F45656;
}

.dialog-tip-text {
  display: inline-block;
  font-size: 18px;
  height: 24px;
  line-height: 24px;
  color: rgba(28, 28, 28, 100);
}

.dialog-view-text {
  color: rgba(28, 28, 28, 100);
  font-size: 12px;
  white-space: pre-line;
}

.payment-status {
  position: absolute;
  top: 0;
  right: 20px;
  color: rgba(223, 78, 42, 100);
  font-size: 14px;
}

.file-name {
  cursor: pointer;
  text-decoration: underline;
}
</style>
